package 二叉树;


import java.util.ArrayList;
import java.util.List;

public class q257二叉树的所有路径 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> res = new ArrayList<>();
            if (root == null) {
                return res;
            }
            List<Integer> paths = new ArrayList<>();// 作为结果中的路径
            traversal(root, paths, res);
            return res;
        }

        public void traversal(TreeNode root, List<Integer> paths, List<String> res) {

            paths.add(root.val);
            // 叶子节点
            if (root.left == null && root.right == null) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < paths.size() - 1; i++) {
                    sb.append(paths.get(i)).append("->");
                }
                sb.append(paths.get(paths.size() - 1)); // 最后一个不加箭头
                res.add(sb.toString());
                return;
            }
            // 递归和回溯是同时进行，所以要放在同一个花括号里
            if (root.left != null) { // 左
                traversal(root.left, paths, res);
                paths.remove(paths.size() - 1);// 回溯
            }
            if (root.right != null) { // 右
                traversal(root.right, paths, res);
                paths.remove(paths.size() - 1);// 回溯
            }
        }
    }
}
